package cc.deng.wubo.minapp.service.impl;


import cc.deng.wubo.minapp.beans.FileUploadInfo;
import cc.deng.wubo.minapp.component.FileProperties;
import cc.deng.wubo.minapp.core.base.BaseServiceImpl;
import cc.deng.wubo.minapp.service.FileUploadService;
import org.apache.tomcat.util.http.fileupload.FileUpload;
import org.nutz.dao.Dao;
import org.nutz.lang.Files;
import org.nutz.lang.random.R;
import org.nutz.lang.util.Disks;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class FileUploadServiceImpl extends BaseServiceImpl<FileUploadInfo> implements FileUploadService {
    @Autowired
    public FileUploadServiceImpl(Dao dao) {
        super(dao);
    }
    @Autowired
    private FileProperties properties;






    @Override
    public void deleteFile(Long fid) {

        FileUploadInfo fileUploadInfo = dao().fetch(FileUploadInfo.class, fid);
        if (fileUploadInfo!=null){
            String path = fileUploadInfo.getServerPath();
            Files.deleteFile(new File(path));
        }



    }
    /**
     * 传入临时文件路径,返回该文件对象
     * @param filePaths
     * @return
     */
    @Override
    public List<FileUploadInfo> upload(List<String> filePaths) {

        List<FileUploadInfo> uploadInfoList = new ArrayList<>();
        for (String filePath:filePaths){
            File file = new File(filePath);
            FileUploadInfo fileUploadInfo = new FileUploadInfo();
            fileUploadInfo.setExName(Files.getSuffixName(file));
            String serverPath = this.getPath();
            serverPath+= R.UU16()+"."+fileUploadInfo.getExName();
            fileUploadInfo.setServerPath(serverPath);
            uploadInfoList.add(fileUploadInfo);
            Files.copy(file,new File(serverPath));
        }
        this.insert(uploadInfoList);


        return uploadInfoList;
    }


    private String getPath(){
        String filePath = properties.getFilepath();
        DateFormat df = new SimpleDateFormat("yyyyMM");
        String finderName = df.format(new Date());
        String path = filePath+File.separator+finderName+File.separator;
        File finderFile = new File(Disks.normalize(path));
        synchronized (finderFile){
            Files.createDirIfNoExists(finderFile);
        }
        return finderFile.getAbsolutePath()+File.separator;
    }

}
